<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>websocket测试</title>
  </head>

  <body>
    <input type="text" id="demo" value="22" />
    <button id="btn">发送请求</button>
    <div id="res">接收到的服务器端消息显示区域</div>
  </body>
</html>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
  let input = document.getElementById("demo");
  let btn = document.getElementById("btn");

  var ws = new WebSocket("ws://localhost:9999");
  //监听建立连接
  ws.onopen = function (res) {
    console.log(res);
    ws.send("start");
  };
  setTimeout(() => {
    // ws.send("end")
  }, 20 * 1000);
  //监听消息
  ws.onmessage = function (res) {
    console.log("客户端接收到了服务端发来的消息");
    console.log(JSON.parse(res.data));
    let a = JSON.parse(res.data);
    input.value = a.name + a.age + a.sex;
  };
  btn.onclick = function () {
    console.log(input.value);
    ws.send("start1");
  };
</script>
